package com.runyu.cordova.plugin.barcode;

import java.util.ArrayList;
import java.util.List;

import org.apache.cordova.CordovaInterface;

import com.honeywell.aidc.AidcManager;
import com.honeywell.aidc.AidcManager.CreatedCallback;

import android.app.Activity;

public class BarcodeMananger {

	private List<AidcManagerCreatedListener> aidcManagerCreatedListeners = new ArrayList<>();

	private AidcManager aidcManager;

	private static final BarcodeMananger instance;

	private BarcodeMananger() {

	}

	static {
		instance = new BarcodeMananger();
	}

	public static BarcodeMananger getInstance() {
		return instance;
	}

	public void init(CordovaInterface cordovaInterface) {
		Activity activity = cordovaInterface.getActivity();
		AidcManager.create(activity.getApplicationContext(), new CreatedCallback() {

			@Override
			public void onCreated(AidcManager aidcManager) {
				synchronized (BarcodeMananger.this.aidcManagerCreatedListeners) {
					for (AidcManagerCreatedListener aidcManagerCreatedListener : aidcManagerCreatedListeners) {
						aidcManagerCreatedListener.onCreated(aidcManager);
					}
				}
			}
		});
	}

	public void registerAidcManagerCreatedListener(AidcManagerCreatedListener aidcManagerCreatedListener) {
		if (this.aidcManager != null) {
			aidcManagerCreatedListener.onCreated(aidcManager);
			return;
		}
		synchronized (this.aidcManagerCreatedListeners) {
			if (this.aidcManager != null) {
				aidcManagerCreatedListener.onCreated(aidcManager);
				return;
			}
			this.aidcManagerCreatedListeners.add(aidcManagerCreatedListener);
		}
	}

}
